//
//  Mail_Send_Task.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-2-12.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "Mail_Send_Task.h"
#import "EpointStringUtil.h"
#import "SingleFile.h"


@implementation Mail_Send_Task

- (void)execute {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *ValidateData = [EpointBizTools getToken];
    NSString *url = self.getMobileOAWebserviceURL;
    NSString *wsNamespace = NSLocalizedString(@"Epoint_DNet_WS_NameSpace", @"");
    NSString *userguid = [userDefaults objectForKey:Epoint_User_UserGuid];
    NSString *Subject = [params objectForKey:@"Subject"];
    NSString *ToUserGuidList = [params objectForKey:@"ToUserGuidList"];
//    NSString *SecretUserGuidList = [params objectForKey:@"SecretUserGuidList"];
    NSString *SecretUserGuidList = @"";
    NSString *ChaoSongUserGuidList = [params objectForKey:@"ChaoSongUserGuidList"];
    NSString *IFNotice = [params objectForKey:@"IFNotice"];
    NSString *MailContent = [params objectForKey:@"MailContent"];
    NSMutableArray *ATTACHList = [params objectForKey:@"ATTACHList"];
    NSString *strOutboxGuid= [params objectForKey:@"strOutboxGuid"];
    
    if (![self upLoadAttachFile:ATTACHList:strOutboxGuid:@""]) {
        [self exeFailureWithMessage:@"附件上传失败"];
        return;
    }
    
    NSMutableString *attachXML = [[NSMutableString alloc]initWithString:@""];
    [attachXML appendString:@"<ATTACHList>"];
    [attachXML appendString:@""];
    [attachXML appendString:@"</ATTACHList>"];
    
//    EpointWebServiceUtil *ws = [[EpointWebServiceUtil alloc]initWithUrl:url namespace:wsNamespace method:@"Mail_Send"];
    
    NSString *ParasXml = @"<![CDATA[<?xml version=\"1.0\" encoding=\"gb2312\"?><paras><UserGuid>%@</UserGuid><Subject>%@</Subject><ToUserGuidList>%@</ToUserGuidList><SecretUserGuidList>%@</SecretUserGuidList><ChaoSongUserGuidList>%@</ChaoSongUserGuidList><MailContent>%@</MailContent><IFNotice>%@</IFNotice><OutboxGuid>%@</OutboxGuid>%@</paras>]]>";
    Subject = [EpointStringUtil filterXmlString:Subject];
    MailContent = [EpointStringUtil filterXmlString:MailContent];
    ParasXml = [NSString stringWithFormat:ParasXml,userguid,Subject,ToUserGuidList,SecretUserGuidList,ChaoSongUserGuidList,MailContent,IFNotice,strOutboxGuid,attachXML];
    
//    [ws addParameterForString:@"ValidateData" value:ValidateData];
//    [ws addParameterForString:@"ParasXml" value:ParasXml];
//    NSString *bs = ws.start;
    
//    if ([self validateXMLWS:bs]) {
////        [self exeSuccessWithData:[self getLst:bs]];
//        [self sendDataRefreshUI:@[@"1", @"发送成功！"]];
//    }
    if (![self isNetWorkAvailable])
    {
        [self exeFailureWithMessage:FailToLoadNetWorkPleaseCheckTheSetting];
    }
    else
    {
        //请求接口
        EpointWebServiceUtil *ws = [[EpointWebServiceUtil alloc]initWithUrl:url namespace:wsNamespace method:@"Mail_Send"];
        [ws addParameterForString:@"ValidateData" value:ValidateData];
        [ws addParameterForString:@"ParasXml" value:ParasXml];
        NSString *bs =  ws.start;
        
        NSMutableArray *result = [self validateXMLWS2:bs];
        NSString *msg = [result objectAtIndex:1];
        if ([[result objectAtIndex:0]isEqualToString:@"1"]) {
            [self sendDataRefreshUI:@[@"1", @"发送成功！"]];
        }
        else
        {
            [self exeFailureWithMessage:msg];
        }
    }
}

-(BOOL)upLoadAttachFile:(NSMutableArray*)list : (NSString*)ClientGuid :(NSString*)type{
    BOOL isUploadFlag=YES;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userguid = [userDefaults objectForKey:Epoint_User_UserGuid];
    for (int i=0; i<list.count; i++) {
        SingleFile* file = [list objectAtIndex:i];
        NSString *ValidateData = [EpointBizTools getToken];
        NSString *urlString = self.getMobileOAWebserviceURL;
        
       urlString= [urlString stringByReplacingOccurrencesOfString:@"OAWebService.asmx" withString:@"UpdateAttachFile.aspx"];
        urlString = [NSString stringWithFormat:@"%@?AttachGuid=%@&AttachName=%@&ClientGuid=%@&ValidateData=%@&type=%@&userguid=%@",urlString,file.AttachGuid,file.ATTACHFILENAME,ClientGuid,ValidateData,type,userguid];
      
        urlString= (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, nil, nil, kCFStringEncodingUTF8));
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:urlString]];
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",@"******"];
        //结束符 AaB03x--
//        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
   
        NSMutableString *filename = [[NSMutableString alloc] init];
        
        //添加分界线，换行
        [filename appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称，换2行
        [filename appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"AttachName"];
        //添加字段的值
        [filename appendFormat:@"%@\r\n",file.ATTACHFILENAME];
        [filename appendFormat:@"%@\r\n",MPboundary];
        
        
        [filename appendString:@"--******\r\nContent-Disposition:form-data;name=\"file\"; filename=\""];
        [filename appendString:file.ATTACHFILENAME];
        [filename appendString:@"\"\r\nContent-Type: image/png\r\n\r\n"];
        [request setHTTPMethod:@"POST"];
        NSMutableData * inputData =[[NSMutableData alloc] init];
        [inputData appendData:[filename dataUsingEncoding:NSUTF8StringEncoding]];
        [inputData appendData:file.fileData];
        NSMutableString *filename1 = [[NSMutableString alloc] init];
        [filename1 appendString:@"\r\n"];
        [filename1 appendString:@"--******--"];
        [inputData appendData:[filename1 dataUsingEncoding:NSUTF8StringEncoding]];
        //set headers
        [request addValue:@"multipart/form-data;boundary=******" forHTTPHeaderField: @"Content-Type"];
        [request addValue:@"multipart/form-data" forHTTPHeaderField: @"enctype"];
        [request addValue:@"Keep-Alive" forHTTPHeaderField: @"Connection"];
        [request addValue:@"UTF-8" forHTTPHeaderField: @"Charset"];
        [request addValue:[NSString stringWithFormat:@"%d",inputData.length] forHTTPHeaderField: @"Content-Length"];

        [request setHTTPBody:inputData];
        //get response
        NSHTTPURLResponse* urlResponse = nil;
        NSError *error = [[NSError alloc] init];
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
        NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"Response Code: %d", [urlResponse statusCode]);
        if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
            NSLog(@"Response: %@", result);
            isUploadFlag = YES;
        }else{
            isUploadFlag=NO;
            break;
        }
    }
    return isUploadFlag;
}

-(BOOL)upLoadZWBJFile:(NSData*)fileData :(NSString*)MessageItemGuid {
    BOOL isUploadFlag=YES;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userguid = [userDefaults objectForKey:Epoint_User_UserGuid];
        NSString *ValidateData = [EpointBizTools getToken];
        NSString *urlString = self.getMobileOAWebserviceURL;
        
        urlString= [urlString stringByReplacingOccurrencesOfString:@"OAWebService.asmx" withString:@"UpdateAttachFile.aspx"];
        urlString = [NSString stringWithFormat:@"%@?MessageItemGuid=%@&AttachName=%@&ValidateData=%@&type=%@&userguid=%@",urlString,MessageItemGuid,@"发文原稿.doc",ValidateData,@"ZWWord",userguid];
        
        urlString= (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, nil, nil, kCFStringEncodingUTF8));
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:urlString]];
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",@"******"];
        //结束符 AaB03x--
        //        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
        
        NSMutableString *filename = [[NSMutableString alloc] init];
        
        //添加分界线，换行
        [filename appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称，换2行
        [filename appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"AttachName"];
        //添加字段的值
        [filename appendFormat:@"%@\r\n",@"zwbj.doc"];
        [filename appendFormat:@"%@\r\n",MPboundary];
        
        
        [filename appendString:@"--******\r\nContent-Disposition:form-data;name=\"file\"; filename=\""];
        [filename appendString:@"zwbj.doc"];
        [filename appendString:@"\"\r\nContent-Type: image/png\r\n\r\n"];
        [request setHTTPMethod:@"POST"];
        NSMutableData * inputData =[[NSMutableData alloc] init];
        [inputData appendData:[filename dataUsingEncoding:NSUTF8StringEncoding]];
        [inputData appendData:fileData];
        NSMutableString *filename1 = [[NSMutableString alloc] init];
        [filename1 appendString:@"\r\n"];
        [filename1 appendString:@"--******--"];
        [inputData appendData:[filename1 dataUsingEncoding:NSUTF8StringEncoding]];
        //set headers
        [request addValue:@"multipart/form-data;boundary=******" forHTTPHeaderField: @"Content-Type"];
        [request addValue:@"multipart/form-data" forHTTPHeaderField: @"enctype"];
        [request addValue:@"Keep-Alive" forHTTPHeaderField: @"Connection"];
        [request addValue:@"UTF-8" forHTTPHeaderField: @"Charset"];
        [request addValue:[NSString stringWithFormat:@"%d",inputData.length] forHTTPHeaderField: @"Content-Length"];
        
        [request setHTTPBody:inputData];
        //get response
        NSHTTPURLResponse* urlResponse = nil;
        NSError *error = [[NSError alloc] init];
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
        NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"Response Code: %d", [urlResponse statusCode]);
        if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
            NSLog(@"Response: %@", result);
            isUploadFlag = YES;
        }else{
            isUploadFlag=NO;
        }
    return isUploadFlag;
}

@end
